package design.pattern.Lu15CompositePattern;

import java.util.ArrayList;
import java.util.List;

/**
 * @program JavaBase
 * @description: 组合模式 -父级子级
 * @author: zhanglu
 * @create: 2020-04-10 09:05:00
 */
public class CompositePattern04 {

    public static void main(String[] args) {

        Corp04 r1 = new Branch04("A");
        Corp04 b1 = new Branch04("B");
        Corp04 b2 = new Branch04("C");
        Corp04 b3 = new Branch04("D");

        Leaf04 l1 = new Leaf04("a");
        Leaf04 l2 = new Leaf04("b");
        Leaf04 l3 = new Leaf04("c");
        Leaf04 l4 = new Leaf04("d");
        Leaf04 l5 = new Leaf04("bb");

        r1.add(l1);
        r1.add(b1);
        r1.add(b2);
        r1.add(b3);

        b1.add(l2);
        b1.add(l5);

        b2.add(l3);

        b3.add(l4);

        //遍历孩子
//        childShow(r1);

        //遍历父亲
        parentShow(l2);

        parentShow(l5);

    }

    public static void childShow(Corp04 corp04){
        for (Corp04 c : corp04.getList()) {
            if(c instanceof Leaf04){
                c.print();
            }else {
                c.print();
                childShow(c);
            }
        }
    }

    public static void parentShow(Corp04 corp04){
        Corp04 p = corp04.getParent();
        p.print();
        if(p.getParent() != null){
            parentShow(p);
        }
    }

}

abstract class Corp04{

    private Corp04 corp04;
    private String name;

    public Corp04(String name){
        this.name = name;
    }

    protected abstract void add(Corp04 corp04);

    protected abstract List<Corp04> getList();

    protected void setParent(Corp04 corp04){
        this.corp04 = corp04;
    }

    protected Corp04 getParent(){
        return this.corp04;
    }

    protected void print(){
        System.out.println("输出：" + this.name);
    }

}

class Leaf04 extends Corp04{

    public Leaf04(String name) {
        super(name);
    }

    @Deprecated
    protected void add(Corp04 corp04) {

    }

    @Deprecated
    protected List<Corp04> getList() {
        return null;
    }
}

class Branch04 extends Corp04{

    private List<Corp04> childList = new ArrayList<>();

    public Branch04(String name) {
        super(name);
    }

    @Override
    protected void add(Corp04 corp04) {
        corp04.setParent(this);
        this.childList.add(corp04);
    }

    @Override
    protected List<Corp04> getList() {
        return this.childList;
    }
}
